//
//  SWUserAccount.swift
//  SinaWeibo
//
//  Created by AenyMo on 16/3/31.
//  Copyright © 2016年 AenyMo. All rights reserved.
//

import UIKit

class SWUserAccount: NSObject, NSCoding {
    //access_token
    var access_token: String?
    //access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        //重写set方法
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expires_date: NSDate?
    
    //授权用户的UID
    var uid: String?
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    //用户名
    var name: String?
    
    //MARK: - 初始化
    init(dict: [String: AnyObject]) {
        super.init()
        //KVC赋值
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    //重写打印函数    控制台打印时执行
    override var description: String {
        let keys = ["access_token", "uid", "avatar_large", "name", "expires_date"]
        return dictionaryWithValuesForKeys(keys).description
        
    }
    
    //MARK: - 归档 反归档
    func saveAccountToSanbox(){
        //
        let filePath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.info")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
    class func loadAccountFromSanbox() -> SWUserAccount? {
        
        let filePath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.info")
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? SWUserAccount {
            //如果有值
            //判断是否过期
            if account.expires_date?.compare(NSDate()) != NSComparisonResult.OrderedAscending {
                
                //如果没过期,才返回
                return account
            }
        }
        //默认,返回nil
        return nil
    }
    
    // MARK: - 要使用归档,必须实现NSCoding协议方法
    func encodeWithCoder(aCoder: NSCoder) {
        //
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
    }
    required init?(coder aDecoder: NSCoder) {
        //
        super.init()
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
    }

}


